﻿using System;
using System.Collections.Generic;
using GalaSoft.MvvmLight.Messaging;
using Holdem.Core.Entities.Collections;
using Holdem.Interfaces.Configuration;
using Holdem.Interfaces.HandHistory;
using Holdem.Interfaces.Messages;
using Holdem.Interfaces.Model;
using Holdem.Interfaces.ReplayEngine;
using Holdem.Interfaces.Service;

namespace Holdem.Model
{
	public class HoldemHandHistoryModel : IHoldemHandHistoryModel
	{
		private readonly IReplayEngineStrategy<string, IReplayEngine> _engineStrategy;
		private readonly IReplayEngineProvider _engineProvider;
		private readonly IConfigurationService _configurationService;

		/// <summary>
		/// 
		/// Returns the last loaded engine, after calling GetSelectedReplayEngine().
		/// 
		/// </summary>
		public IReplayEngine LastLoadedEngine
		{
			get;
			private set;
		}

		#region Constructor

		public HoldemHandHistoryModel(
			IReplayEngineStrategy<string, IReplayEngine> engineStrategy,
			IReplayEngineProvider engineProvider,
			IConfigurationService configurationService)
		{
			if (engineStrategy == null)
				throw new ArgumentNullException("engineStrategy");
			if (engineProvider == null)
				throw new ArgumentNullException("engineProvider");
			if (configurationService == null)
				throw new ArgumentNullException("configurationService");

			_engineStrategy = engineStrategy;
			_engineProvider = engineProvider;
			_configurationService = configurationService;
		}

		#endregion //Constructor

		#region IHoldemHandHistoryModel Implementation

		//public event EventHandler<HoldemHandHistoryGeneratedEventArgs> HandHistoryGenerated;

	    public bool HasHistory()
	    {
	        this.SetCurrentReplayEngine();

	        return this.LastLoadedEngine.HasHandReplay();
	    }

	    public void GetHandHistory()
        {
            IEnumerable<History> handHistory = new HandHistoryWriterCollection();

            SetCurrentReplayEngine();

            if( this.LastLoadedEngine != null )
                handHistory = this.LastLoadedEngine.GetHandReplay(_engineProvider);

            Messenger.Default.Send(new HandHistoryGeneratedMessage(handHistory));

            //if( this.HandHistoryGenerated != null )
            //this.HandHistoryGenerated(this, new HoldemHandHistoryGeneratedEventArgs(handHistory));
        }

	    private void SetCurrentReplayEngine()
        {
            var savedSelection = _configurationService.PersistentConfiguration.Cast<string>(ConfigKey.HoldemOptionsViewSelectedReplayEngine);

            this.LastLoadedEngine = _engineStrategy.GetStrategy(savedSelection);
        }

		#endregion //IHoldemHandHistoryModel Implementation
	}
}